package com.ssm.upms.rpc.service.impl;

import com.ssm.upms.dao.mapper.ssm.AccountDao;
import com.ssm.upms.dao.mapper.ssm.AdminDao;
import com.ssm.upms.dao.mapper.ssm.PowerDao;
import com.ssm.upms.dao.mapper.ssm.RoleDao;
import com.ssm.upms.dao.model.Account;
import com.ssm.upms.dao.model.Admin;
import com.ssm.upms.dao.model.Power;
import com.ssm.upms.dao.model.Role;
import com.ssm.upms.rpc.api.UserUpmsApiService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Easy on 2017-07-27.
 */
public class UserUpmsApiServiceImpl implements UserUpmsApiService {
    @Resource
    private RoleDao roleDao;
    @Resource
    private AccountDao accountDao;
    @Resource
    private PowerDao powerDao;
    @Resource
    private AdminDao adminDao
;    @Override
    public List<Role> findByAccountId(String accountId)  {
        try {
          return roleDao.findByAccountId(accountId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public List<Power> findByRoleId(String roleId) {
        try {

            return powerDao.findByRoleId(roleId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Account findByUserName(String userName) {
        try {
            return accountDao.findByUserName(userName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据 id 查找
     * @param id 实体id
     * @return 实体
     * @throws Exception 查询异常
     */
    public Admin selectById(String id) {
        return adminDao.selectById(id);
    }

    @Override
    public List<Power> findByAccountPId(String accountId) {

        List<Power> p = powerDao.findByAccountId(accountId);
        return getPowers(p);
    }
    public List<Power> getPowers(List<Power> p) {
        List<Power> menu = searchListByParentId(p,"0");
        for(Power pp : menu){
            pp.setPowers(searchListByParentId(p,pp.getId()));
            for(Power ppp : pp.getPowers()){
                ppp.setPowers(searchListByParentId(p,ppp.getId()));
            }
        }
        return menu;
    }
    /**
     * 在list中寻找指定parentid的数据 并返回
     * @param list 全部权限
     * @param parentId 父级id
     * @return 所属父级的全部权限
     */
    public List<Power> searchListByParentId(List<Power> list,String parentId){
        List<Power> temp = new ArrayList<>();
        for(Power p : list){
            if(p.getParentId().equals(parentId)){
                temp.add(p);
            }
        }
        return temp;
    }
}
